package com.lzy.business.controller.order;

import com.github.pagehelper.PageInfo;
import com.lzy.business.facade.OrderFacade;
import com.lzy.business.request.MotorOrderRequest;
import com.lzy.business.response.MotorOrderResponse;
import com.lzy.framework.component.PageBean;
import com.lzy.framework.component.ResultVO;
import com.lzy.framework.core.ensure.Ensure;
import com.lzy.framework.core.excel.SimpleExcelExportUtils;
import com.lzy.framework.core.orm.db.Pager;
import com.lzy.framework.core.output.Result;
import com.lzy.framework.core.utils.CollectionUtils;
import com.lzy.framework.core.utils.DozerUtils;
import com.lzy.framework.core.utils.WebUtils;
import com.lzy.framework.tools.kv.KvClient;
import com.lzy.member.dtos.MemberSaleOrderDto;
import com.lzy.order.apis.OrderApi;
import com.lzy.order.constants.OrderDistributePrefix;
import com.lzy.order.constants.OrderSatusDesEnum;
import com.lzy.order.dtos.OrderActionDTO;
import com.lzy.order.dtos.OrderMessageDTO;
import com.lzy.product.constants.OrderBusiConstants;
import com.lzy.web.exception.GenericException;
import com.lzy.web.response.excel.OrderListExportResponse;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;

@Controller
@RequestMapping("admin/order")
public class OrderController {

    private static final Logger logger = LoggerFactory.getLogger(OrderController.class);

    @Autowired
    private OrderFacade orderFacade;

    @Autowired
    private OrderApi orderApi;

    @Autowired
    private KvClient kvClient;

    /**
     * 初始页面:选择
     *
     * @param type
     * @return
     */
    @RequestMapping(value = "orderListPage/{type}", method = RequestMethod.GET)
    public String outDoorListPage(@PathVariable("type") Integer type) {
        return returnStrByType(type);
    }

    /**
     * 手动关闭订单
     *
     * @param orderId
     * @return
     */
    @RequestMapping(value = "close", method = RequestMethod.GET)
    public ResultVO closeOrder(Long orderId) {
        OrderActionDTO oaDTO = new OrderActionDTO();
        oaDTO.setOrderId(orderId);
        oaDTO.setType(Integer.valueOf(String.valueOf(orderId).substring(0, 1)));
        orderApi.cancle(oaDTO);
        // 发送消息（订单超时关闭）
        OrderMessageDTO dto = new OrderMessageDTO();
        dto.setOrderId(oaDTO.getOrderId());
        dto.setMinStatus(OrderSatusDesEnum.GUIDE_CAMP.getStatus());
        kvClient.addQueue(OrderDistributePrefix.QueueOrder.QUEUE_ORDER_MESSAGE, dto);
        return new ResultVO();
    }

    private String returnStrByType(Integer type) {
        String str = null;
        switch (type + "") {
            /**  */
            case OrderBusiConstants.Biz.PRODUCT:
                str = "order/product/order_tab";
                break;
            case OrderBusiConstants.Biz.COUPONS:
                str = "order/coupons/order_tab";
                break;
            default:
                Ensure.that(true).isFalse("01000801");
        }
        return str;
    }

    /**
     * 转向销售订单列表页面
     *
     * @return
     */
    @RequestMapping(value = "motorOrderList", method = RequestMethod.GET)
    public String motorOrderList() {
        return "salesOrder/sales_tab";
    }

    @RequestMapping(value = "motorOrder/{status}", method = RequestMethod.GET)
    public String orderList(@PathVariable("status") Integer status, Model model) {
        model.addAttribute("status", status);
        if (status!=null && status.equals(3))
            return "salesOrder/hasPay_list";
        return "salesOrder/sales_list";
    }

    /**
     * 查询销售订单列表
     *
     * @param request 查询条件
     * @return
     */
    @RequestMapping(value = "motorOrderList/{status}", method = RequestMethod.GET)
    @ResponseBody
    public PageBean motorOrderList(@PathVariable("status") Integer status, MotorOrderRequest request) {
        Ensure.that(request).isNotNull("04000001");
        Pager pager = new Pager();
        pager.setPageSize(request.getPageSize());
        pager.setPageNum(request.getPageNum());
        if (null != status && status != -1) {
            request.setStatus(status);
        } else {
            request.setStatus(null);
        }
        PageInfo<MemberSaleOrderDto> pageInfo = orderFacade.motorOrderList(pager, DozerUtils.map(request, MemberSaleOrderDto.class));
        if (pageInfo != null && pageInfo.getList()!=null && pageInfo.getList().size()>0) {
            return new PageBean<>(pageInfo.getTotal(), DozerUtils.maps(pageInfo.getList(), MotorOrderResponse.class));
        }
        return null;
    }

    /**
     * 查询销售订单列表
     *
     * @param request 查询条件
     * @return
     */
    @RequestMapping(value = "dataStatistics", method = RequestMethod.GET)
    @ResponseBody
    public Result dataStatistics(MotorOrderRequest request) {
        Result result = new Result();
        result.setResult(orderFacade.dataStatistics(DozerUtils.map(request, MemberSaleOrderDto.class)));
        return result;
    }

    /**
     * 查看订单详情
     *
     * @param model
     * @param orderId 订单ID
     * @return
     */
    @RequestMapping(value = "orderDetail/{orderId}", method = RequestMethod.GET)
    public String orderProductDetail(Model model, @PathVariable("orderId") String orderId) {
        MemberSaleOrderDto memberSaleOrderDto = new MemberSaleOrderDto();
        memberSaleOrderDto.setKey(orderId);
        memberSaleOrderDto.setOrderId(orderId);
        PageInfo<MemberSaleOrderDto> pageInfo = orderFacade.motorOrderList(null, memberSaleOrderDto);
        if (pageInfo!=null && pageInfo.getList()!=null && pageInfo.getList().size()>0) {
            model.addAttribute("orderProductDto", pageInfo.getList().get(0));
            return "salesOrder/sales_view";
        } else {
            return "";
        }
    }


    /**
     * 导出订单
     *
     * @param request
     * @param response
     * @param motorOrderRequest
     */
    @RequestMapping(value = "/exportOrderList")
    public void exportOrderList(HttpServletRequest request, HttpServletResponse response, MotorOrderRequest motorOrderRequest) {
        try {
            Pager pager = new Pager();
            pager.setPageSize(10000);
            if (null != motorOrderRequest.getStatus() && motorOrderRequest.getStatus() != -1) {
                motorOrderRequest.setStatus(motorOrderRequest.getStatus());
            } else {
                motorOrderRequest.setStatus(null);
            }
            PageInfo<MemberSaleOrderDto> pageInfo = orderFacade.motorOrderList(pager, DozerUtils.map(request, MemberSaleOrderDto.class));
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            List<MemberSaleOrderDto> list = pageInfo.getList();
            if (CollectionUtils.isNotEmpty(list)) {
                if (list.size() > 10000)
                    throw new GenericException("导出数据量过大,请重新输入检索条件,分批导出！");
                LinkedList<OrderListExportResponse> voList = new LinkedList<>();
                OrderListExportResponse vo;
                for (MemberSaleOrderDto memberSaleOrderDto : list) {
                    vo = new OrderListExportResponse();
                    BeanUtils.copyProperties(memberSaleOrderDto, vo);
                    voList.add(vo);
                }
                SimpleExcelExportUtils excelExportService = new SimpleExcelExportUtils();
                HSSFWorkbook wb = new HSSFWorkbook();
                if (voList != null && voList.size() > 0) {
                    wb = excelExportService.generateExcel(voList);
                }
                String fileName = "销售订单" + sdf.format(new Date()) + ".xls";
                // 设定输出文件头
                WebUtils.prepareDownloadFile(fileName, "application/msexcel", request, response);
                OutputStream out = response.getOutputStream();
                wb.write(out);
                out.close();
            } else {
                logger.error("没有可执行数据：销售订单数据导出EXCEL失败！");
            }
        } catch (Exception e) {
            logger.error("销售订单数据导出EXCEL失败！", e);
            throw new GenericException("销售订单数据导出EXCEL失败");
        }
    }

}
